import { PlusOutlined, LoadingOutlined } from "@ant-design/icons";
import { message, Upload } from "antd";
import { useState } from "react";
import API from './../../api'
import { v4 as uuidv4 } from "uuid";

/**
 * 上传图片
 * 可查阅文档
 * https://cloud.tencent.com/document/product/436/11459
 *
 * @value 当前显示图片的URL
 * @uploadSuccess 上传图片后的地址
 *
 */
export default (props) => {
  const [loading, setLoading] = useState(false);
  const [currentUrl, setCurrentUrl] = useState(null);

  const httpRequest = (req) => {
    setLoading(true);
    const cos = new COS({
      // getAuthorization 必选参数
      getAuthorization: async (options, callback) => {
        const data = await API.getCosAutograph();
        const credentials = data.credentials;
        callback({
          TmpSecretId: credentials.tmpSecretId,
          TmpSecretKey: credentials.tmpSecretKey,
          SecurityToken: credentials.sessionToken,
          // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
          StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
          ExpiredTime: data.expiredTime, // 时间戳，单位秒，如：1580000000
        });
      },
    });
    const fileName = uuidv4();
    cos.putObject(
      {
        Bucket: "yn-1308768202" /* 必须 */,
        Region: "ap-shanghai" /* 存储桶所在地域，必须字段 */,
        Key: fileName /* 必须 */,
        StorageClass: "STANDARD",
        Body: req.file, // 上传文件对象
      },
      (err, data) => {
        setLoading(false);
        if (err) {
          console.log(err, "我是错误");
          message.error(err);
          return;
        }
        props.uploadSuccess && props.uploadSuccess("https://" + data.Location);
        setCurrentUrl("https://" + data.Location);
      }
    );
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        上传图片
      </div>
    </div>
  );

  return (
    <Upload
      name="avatar"
      showUploadList={false}
      listType="picture-card"
      customRequest={httpRequest}
    >
      {currentUrl || props.value ? (
        <img
          src={currentUrl || props.value}
          alt="avatar"
          style={{
            width: "100%",
          }}
        />
      ) : (
        uploadButton
      )}
    </Upload>
  );
};
